package com.classic.core.utils;

import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.GridView;
import android.widget.ListView;

/**
 * Created by Jayden on 2016/4/26 12:06.
 *
 * @version V1.0
 * @Title:
 * @Description: ${todo}
 */
public class ListUtil {

    private ListUtil() {
    }

    /**
     * 重新计算listview高度
     */
    public static void setListViewHeightBasedOnChildren(ListView listView, Adapter adapter) {
        if (adapter == null) {
            return;
        }

        int totalHeight = 0;
        for (int i = 0; i < adapter.getCount(); i++) {
            View listItem = adapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (adapter.getCount() - 1));
        listView.setLayoutParams(params);
    }

    /**
     * 重新计算listview高度
     */
    public static void setListViewHeightBasedOnChildren(GridView listView, Adapter adapter) {
        if (adapter == null) {
            return;
        }

        int totalHeight = 0;
        for (int i = 0; i < adapter.getCount(); i++) {
            View listItem = adapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getHeight() * (adapter.getCount() - 1));
        listView.setLayoutParams(params);
    }
}
